<template>
  <div class="home" style="padding: 10px" ref="homeBoxRef">
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="record" tab="审批中心">
        <div class="record-box" ref="recordBoxRef">
          <div class="left">
            <a-row class="filter-box" :gutter="12">
              <a-col :span="6">
                <a-select
                  v-model:value="filterState.type"
                  :options="recordsTab"
                  style="width: 100%"
                  @select="getRecordList(true)"
                />
              </a-col>
              <a-col :span="6">
                <a-select
                  v-model:value="filterState.status"
                  :options="statusList"
                  style="width: 100%"
                  @select="getRecordList(true)"
                />
              </a-col>
              <a-col :span="12">
                <a-range-picker
                  v-model:value="rangeDate"
                  :ranges="ranges"
                  @change="handleRangePickerChange"
                />
              </a-col>
            </a-row>
            <div class="content beauty-scroller-bar">
              <div v-if="noRecord" class="mt-20">
                <a-empty description="暂无记录" />
              </div>
              <div
                v-for="item of recordList"
                :key="item.arrKey"
                class="mt-20 record-item"
              >
                <a-card
                  size="small"
                  :class="{ active: item.id == currentRecordId }"
                  @click="checkRecordDetail(item)"
                >
                  <template #title>
                    <span class="text-black bold">{{
                      item.approval_name
                    }}</span>
                  </template>
                  <template #extra>
                    <a-tag :color="colorList[item.status]">
                      {{ item.status_txt }}
                    </a-tag>
                  </template>
                  <a-row :gutter="[0, 12]">
                    <a-col
                      :span="24"
                      v-for="(formItem, formItemIndex) of item.form"
                      :key="formItemIndex"
                      class="no-wrap"
                    >
                      <span class="title">{{ formItem.title }}：</span>
                      <span>{{ formItem.content || '--' }}</span>
                    </a-col>
                    <a-col :span="24">
                      <div class="flex between align-middle user">
                        <div class="flex flex-1 align-middle user">
                          <a-avatar
                            :src="item.user_avatar"
                            style="
                              color: #fff;
                              background-color: #2681f3;
                              margin-right: 10px;
                            "
                            :size="24"
                          >
                            <template #icon><UserOutlined /></template>
                          </a-avatar>
                          <span class="flex-1">{{ item.user_name }}</span>
                        </div>
                        <span>{{ item.created_at }}</span>
                      </div>
                    </a-col>
                  </a-row>
                </a-card>
              </div>
            </div>
            <a-row class="pagination-box">
              <a-pagination
                size="small"
                :total="recordTotal"
                :show-total="(total) => `共 ${total} 条`"
                :pageSize="filterState.pageSize"
                v-model:current="filterState.page"
                @change="handlePagerChange"
              />
            </a-row>
          </div>
          <div class="right">
            <detail-show
              :id="currentRecordId"
              @finish="handleApprovalItemFinish"
            />
          </div>
        </div>
      </a-tab-pane>
      <template #rightExtra>
        <a-button type="primary" ghost @click="manageApproval">
          <template #icon>
            <SwapOutlined />
          </template>
          管理后台
        </a-button>
      </template>
    </a-tabs>
  </div>
</template>

<script>
import {
  defineComponent,
  onActivated,
  reactive,
  toRaw,
  toRefs,
  ref,
  nextTick,
} from 'vue'
import { SwapOutlined, UserOutlined } from '@ant-design/icons-vue'
import request from '../../../common/utils/request'
import { useRouter } from 'vue-router'
import DetailShow from '../ApprovalDetail/modules/DetailShow.vue'
import moment from 'moment'
import approval from '../../../store/modules/approval'
import { Modal } from 'ant-design-vue'

const dateFormatStr = 'YYYY-MM-DD'
const ranges = {
  今天: [moment(), moment()],
  本周: [moment().startOf('week'), moment().endOf('week')],
  本月: [moment().startOf('month'), moment().endOf('month')],
  本年: [moment().startOf('year'), moment().endOf('year')],
}

const recordsTab = [
  { value: 'todo', label: '待审批' },
  { value: 'complete', label: '已审批' },
  { value: 'cc', label: '抄送我' },
  { value: 'start', label: '已发起' },
]
const statusList = [
  { value: -1, label: '所有' },
  { value: 0, label: '审批中' },
  { value: 1, label: '已通过' },
  { value: 2, label: '已拒绝' },
  { value: 4, label: '已撤销' },
]
const colorList = {
  0: 'blue',
  1: 'green',
  2: 'red',
  4: 'gray',
}

export default defineComponent({
  name: 'home',
  components: { SwapOutlined, UserOutlined, DetailShow },
  setup() {
    const router = useRouter()
    const state = reactive({
      activeKey: 'record', // approval record
      recordTotal: 0,
      recordList: [],
      noRecord: false,
      currentRecordId: 0,
      rangeDate: [],
    })

    /** 审批中心 */

    const filterState = reactive({
      type: 'todo',
      status: -1,
      page: 1,
      pageSize: 10,
      rangeDate: [],
    })

    const checkRecordDetail = (current) => {
      if (state.currentRecordId == current.id) {
        return
      }
      state.currentRecordId = current.id
    }

    const handleApprovalItemFinish = () => {
      if (filterState.type == 'todo') {
        getRecordList(true)
      }
    }

    const handlePagerChange = (page) => {
      filterState.page = page
      getRecordList()
    }

    const handleRangePickerChange = (date, dateStr) => {
      filterState.rangeDate = dateStr
      getRecordList(true)
    }

    const getRecordList = (init = false) => {
      const params = {
        ...filterState,
      }
      if (init) {
        params.page = 1
      }
      if (params.rangeDate[0] && params.rangeDate[1]) {
        params.createDay = 'diy'
        params.start_day = params.rangeDate[0]
        params.end_day = params.rangeDate[1]
      }
      delete params.rangeDate
      state.recordList = []
      request
        .get('/work_approval', '/tenant/approvalForm/list', params)
        .then((res) => {
          state.recordList = res.list
          state.recordTotal = res.total
          state.noRecord = res.total === 0
          if (init) {
            state.currentRecordId = state.noRecord ? 0 : state.recordList[0].id
          }
        })
    }

    /** 发起审批 */

    const manageApproval = () => {
      router.push({
        name: 'TenantApprovalManage',
      })
    }

    const startApproval = (approval) => {
      if (approval.process.length == 0) {
        Modal.info({
          title: '提示',
          content: () => '请管理员前往管理后台初始化该审批，并完善审批流程',
          centered: true,
        })
        return
      }
      router.push({
        name: 'StartApproval',
        query: { id: approval.id },
      })
    }

    const homeBoxRef = ref(null)
    const recordBoxRef = ref(null)

    const init = () => {
      getRecordList(true)
      nextTick(() => {
        recordBoxRef.value.style.height =
          homeBoxRef.value.offsetHeight - 90 + 'px'
      })
    }

    init()

    return {
      recordsTab,
      colorList,
      statusList,
      filterState,
      dateFormatStr,
      ranges,
      ...toRefs(state),
      manageApproval,
      startApproval,
      checkRecordDetail,
      getRecordList,
      handleApprovalItemFinish,
      handlePagerChange,
      handleRangePickerChange,

      homeBoxRef,
      recordBoxRef,
    }
  },
})
</script>
<style lang="less" scoped>
.home {
  width: 100%;
  height: 100%;
  .approval-box {
    padding: 10px 20px;

    .approval {
      border: 1px solid #fff;
      box-shadow: @box-shadow-base;
      padding: 20px;
      height: 80px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      overflow: hidden;
      cursor: pointer;
      user-select: none;
      .icon {
        width: 44px;
        height: 44px;
        border-radius: 50%;
      }
      .info {
        margin-left: 8px;
        flex: 1;
        line-height: 24px;
        overflow: hidden;
        .name {
          color: rgba(0, 0, 0, 1);
          font-weight: 500;
          font-size: 15px;
        }
        .desc {
          color: rgba(0, 0, 0, 0.6);
        }
      }
    }
  }
  .record-box {
    display: flex;
    overflow: hidden;
    .left {
      width: 460px;
      height: 100%;
      margin-right: 20px;
      position: relative;
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;

      // padding-right: 20px;
      // border-right: 1px solid #f1f1f1;
      .filter-box,
      .pagination-box {
        position: absolute;
        left: 1px;
        right: 1px;
        background: #fff;
        z-index: 1;
        display: flex;
        align-items: center;
        padding: 0 8px;

        // padding-right: 8px;
        // border: 1px solid #ddd;
      }
      .filter-box {
        top: 0;
        border-bottom: 1px solid #ddd;
        height: 50px;
      }
      .pagination-box {
        height: 40px;
        bottom: 0;
        border-top: 1px solid #ddd;
        text-align: right;
        justify-content: flex-end;
      }
      .content {
        padding: 50px 0;
        height: 100%;
        overflow: hidden auto;
        // background: #fefefe;
        .record-item {
          cursor: pointer;
          user-select: none;
          padding: 0 8px;
          // box-shadow: @box-shadow-base;

          .title {
            color: #666;
          }
          .user {
            font-size: 12px;
            color: #999;
          }
        }
        .active {
          border: 1px solid @primary-color;
          background: @primary-color-bg;
        }
      }
    }
    .right {
      flex: 1;
      height: 100%;
      position: relative;
      // box-shadow: @box-shadow-base;
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;
      // margin-right: 20px;
    }
  }
}
:deep(.ant-tabs-nav) {
  border-bottom: 1px solid #f1f1f1;
  margin-bottom: 20px;
}
</style>
